package com.whfc.fmam.xxl.job;

import com.alibaba.fastjson.JSONObject;
import com.whfc.XxlJobConfig;
import com.whfc.common.generator.KeyGeneratorUtil;
import com.whfc.common.util.DateUtil;
import com.whfc.fmam.dao.*;
import com.whfc.fmam.entity.bo.*;
import com.whfc.fmam.entity.dto.FmamMatDetailDTO;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Description 生成物资数据
 * @Author hw
 * @Date 2021-09-10 11:09
 * @Version 1.0
 */
@Component
@ConditionalOnBean(XxlJobConfig.class)
public class FmamDataDemoJob {


    @Autowired
    private FmamWeighNoteMapper fmamWeighNoteMapper;

    @Autowired
    private FmamWeighNoteMatMapper fmamWeighNoteMatMapper;

    @Autowired
    private FmamWeighNoteImgMapper fmamWeighNoteImgMapper;

    @Autowired
    private FmamWeighRoomMapper fmamWeighRoomMapper;

    @Autowired
    private FmamSupplierMapper fmamSupplierMapper;

    @Autowired
    private FmamWarehouseMapper fmamWarehouseMapper;

    @Autowired
    private FmamMatMapper fmamMatMapper;

    @XxlJob("fmamDataDemo")
    public void fmamDataDemo() {
        //编造物资数据
        XxlJobHelper.log("开始生成物资数据...");
        String paramStr = XxlJobHelper.getJobParam();
        if (StringUtils.isEmpty(paramStr)) {
            XxlJobHelper.handleSuccess("没有需要伪造数据的deptIds");
            return;
        }
        JSONObject param = JSONObject.parseObject(paramStr);
        List<Integer> deptIds = param.getJSONArray("deptIds").toJavaList(Integer.class);
        List<Date> times = new ArrayList<>();
        if (param.containsKey("startTime") && param.containsKey("endTime")) {
            Date startTime = param.getDate("startTime");
            Date startDate = DateUtil.getDateBegin(startTime);
            Date endTime = param.getDate("endTime");
            Date endDate = DateUtil.getDateEnd(endTime);
            times = DateUtil.getDayListOfMinute(startDate, endDate, 60);
        } else {
            times.add(new Date());
        }

        for (Date time :times) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(time);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            //只生成 6点至22点的数据
            if (hour < 6 || hour > 22) {
                XxlJobHelper.log("没有到生成的时间");
                continue;
            }
            //三分之一的几率生成数据
            Random random = new Random();
//            int i = random.nextInt(3);
//            if (i != 0) {
//                XxlJobHelper.log("几率不对！这次就不生成了");
//                continue;
//            }
            Date date = calendar.getTime();
            for (Integer deptId : deptIds) {
                String plate = generateCarPlate();
                //保存磅单信息
                FmamWeighNote fmamWeighNote = fmamWeighNoteMapper.getRandomWeighNote();
                FmamWeighNote weighNote = new FmamWeighNote();
                BeanUtils.copyProperties(fmamWeighNote, weighNote);
                long weighNoteId = KeyGeneratorUtil.genLongId();
                String guid = UUID.randomUUID().toString().replace("-", "");
                weighNote.setId(weighNoteId);
                weighNote.setGuid(guid);
                weighNote.setDeptId(deptId);
                weighNote.setDate(date);
                weighNote.setLicensePlate(plate);
                FmamWeighRoom weighRoom = fmamWeighRoomMapper.getRandomWeighRoom(deptId);
                String roomCode = fmamWeighNote.getWeighRoomCode();
                if (weighRoom != null) {
                    weighNote.setWeighRoomId(weighRoom.getId());
                    weighNote.setWeighRoomCode(weighRoom.getCode());
                    weighNote.setWeighRoomName(weighRoom.getName());
                    roomCode = weighRoom.getCode();
                }
                StringBuilder sb = new StringBuilder();
                int num = random.nextInt(100);
                sb.append(DateUtil.formatDate(date, "yyyyMMdd")).append("-")
                        .append("WHCXKJZJ").append("-").append(roomCode)
                        .append("-").append("000").append(num);
                weighNote.setCode(sb.toString());
                Integer weightNoteType = fmamWeighNote.getWeightNoteType();
                weighNote.setWeightNoteType(weightNoteType);
                weighNote.setRecvSendType(fmamWeighNote.getRecvSendType());
                //1-收料 2-发料)
                Integer category = weightNoteType == 1 || weightNoteType == 2 ? weightNoteType : null;
                if(category==1){
                    category = 2;
                }else {
                    category = 1;
                }
                FmamSupplier supplier = fmamSupplierMapper.getRandomSupplier(deptId, category);
                if (supplier != null) {
                    switch (weightNoteType) {
                        case 1:
                            weighNote.setSendSupplierId(supplier.getId());
                            weighNote.setSendSupplierName(supplier.getName());
                            break;
                        case 2:
                            weighNote.setReceiveSupplierId(supplier.getId());
                            weighNote.setReceiveSupplierName(supplier.getName());
                            break;
                        default:
                            weighNote.setSendSupplierId(supplier.getId());
                            weighNote.setSendSupplierName(supplier.getName());
                            weighNote.setReceiveSupplierId(supplier.getId());
                            weighNote.setReceiveSupplierName(supplier.getName());
                            break;
                    }
                }
                FmamWarehouse wareHouse = fmamWarehouseMapper.getRandomWareHouse(deptId);
                if (wareHouse != null) {
                    weighNote.setWarehouseId(wareHouse.getId());
                    weighNote.setWarehouseName(wareHouse.getName());
                }
                weighNote.setGrossWeightTime(date);
                weighNote.setTareWeightTime(date);
                weighNote.setPartId(null);
                weighNote.setPartName(null);
                weighNote.setCreateTime(null);
                weighNote.setUpdateTime(null);
                fmamWeighNoteMapper.insertSelective(weighNote);
                //保存材料信息
                List<FmamWeighNoteMat> fmamWeighNoteMatList = fmamWeighNoteMatMapper.selectWeighNoteMatList(fmamWeighNote.getGuid());
                List<FmamWeighNoteMat> matList = new ArrayList<>();
                for (FmamWeighNoteMat fmamNoteMatDTO : fmamWeighNoteMatList) {
                    FmamWeighNoteMat fmamWeighNoteMat = new FmamWeighNoteMat();
                    BeanUtils.copyProperties(fmamNoteMatDTO, fmamWeighNoteMat);
                    fmamWeighNoteMat.setId(KeyGeneratorUtil.genLongId());
                    fmamWeighNoteMat.setGuid(UUID.randomUUID().toString().replace("-", ""));
                    fmamWeighNoteMat.setWeighNoteGuid(guid);
                    FmamMatDetailDTO mat = fmamMatMapper.getRandomMat(deptId);
                    if (mat != null) {
                        fmamWeighNoteMat.setMatTypeId(mat.getMatTypeId());
                        fmamWeighNoteMat.setMatTypeCode(mat.getMatTypeCode());
                        fmamWeighNoteMat.setMatTypeName(mat.getMatTypeName());
                        fmamWeighNoteMat.setMatId(mat.getId());
                        fmamWeighNoteMat.setMatCode(mat.getCode());
                        fmamWeighNoteMat.setMatName(mat.getName());
                    }
                    matList.add(fmamWeighNoteMat);
                }
                if (!matList.isEmpty()) {
                    fmamWeighNoteMatMapper.batchInsert(matList);
                }
                //保存图片
                List<FmamWeighNoteImg> weighNoteImgDTOList = fmamWeighNoteImgMapper.selectWeighNoteImgList(fmamWeighNote.getGuid());
                List<FmamWeighNoteImg> imgList = new ArrayList<>();
                for (FmamWeighNoteImg fmamWeighNoteImgDTO : weighNoteImgDTOList) {
                    FmamWeighNoteImg fmamWeighNoteImg = new FmamWeighNoteImg();
                    BeanUtils.copyProperties(fmamWeighNoteImgDTO, fmamWeighNoteImg);
                    fmamWeighNoteImg.setId(KeyGeneratorUtil.genLongId());
                    fmamWeighNoteImg.setGuid(UUID.randomUUID().toString().replace("-", ""));
                    fmamWeighNoteImg.setWeighNoteGuid(guid);
                    imgList.add(fmamWeighNoteImg);
                }
                if (!imgList.isEmpty()) {
                    fmamWeighNoteImgMapper.batchInsert(imgList);
                }
            }
        }
    }

    /**
     * 生成随机车牌号
     *
     * @return 车牌号
     */
    private String generateCarPlate() {
        String alphas = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        Random random = new Random();
        StringBuilder plate = new StringBuilder();
        plate.append("鄂A");
        // 5位数字/字母
        for (int i = 0; i < 5; i++) {
            plate.append(alphas.charAt(random.nextInt(36)));
        }
        return plate.toString();
    }
}
